package examples;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3, new ThreadFactory() {
            AtomicInteger i = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "pool-thread-" + i);
            }
        });

        System.out.println("submit方法：");
        Future<String> future = threadPool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000);
                return "ok";
            }
        });
        String s = future.get();
        System.out.println(s);


        System.out.println("invokeAll 方法");
        List<Future<String>> futures = threadPool.invokeAll(Arrays.asList(
                ()->{
                    Thread.sleep(1000);
                    return "t1";
                },
                ()->{
                    Thread.sleep(500);
                    return "t2";
                },
                ()->{
                    Thread.sleep(2000);
                    return "t3";
                }
        ));

        futures.forEach((f) -> {
            try {
                String s1 = f.get();
                System.out.println(s1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
